<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Backyard extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->helper(array('form', 'url'));
		$this->load->config('publisher', TRUE);
		$this->load->config('adsense', TRUE);
		$this->load->library('adgeek_view');
		$this->load->library('form_validation');
		$this->load->library('security');
		$this->load->library('session');
		$this->load->library('tank_auth');
		$this->load->library('soapclientnusoap');
		$this->load->library('google-api-php-client/AdSenseHostAuth_admin');
		$this->load->model('publisher');
		$this->lang->load('tank_auth');
		define('LIB_DOC_ROOT', $_SERVER['DOCUMENT_ROOT'].'/application/libraries/google-api-php-client/');
		$this->session_id = $this->session->userdata('session_id');
	}

	function index()
	{	
		if (!$this->tank_auth->is_logged_in()) { // logged in
            redirect('/auth/login');
        }
		else{
			redirect('/backyard/show_publishers');
		}
	}
	
	function authtocallback(){
		$data = $this->input->get(NULL, TRUE);
		if(isset($data['error']) && $data['error'] == 'access_denied'){
			redirect('account/create_failed');	
		}
		
		$this->adsensehostauth_admin->authenticate('adgeek_backyard',$data['code']);
		redirect('/backyard/show_publishers');
	}
	
	function show_publishers(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$publisher = array();
			$publisher['table_header'] = $this->config->item('show_header', 'publisher');
			$publisher['publisher_info'] = $this->publisher->get_publishers_overview();
			//echo "<pre>";print_r($publisher);echo "</pre>";exit;
			//$publisher['bulkApprovalStatus'] = $this->get_bulk_approval_status($publisher['publisher_info']);
			$publisher['bulkAssociationStatus'] = $this->get_bulk_association_status($publisher['publisher_info']);
			//echo "<pre>";print_r($publisher);echo "</pre>";exit;
			$this->load->view('backyard/show_publishers', $publisher);	
		}
	}
	
	function get_bulk_approval_status($publishers){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$this->config->item('developer_client_id', 'adsense')."</client_id>";
		$header = $email . $password . $client_id;
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		$client->setHeaders($header);
		// setting the parameter
		$clientIds = '';
		foreach($publishers as $child_key=>$child_val){
			if(!empty($child_val['googleID_ContentAds'])){
				$clientIds .= '<clientIds>'.$child_val['googleID_ContentAds'].'</clientIds>';
			}
			elseif(!empty($child_val['googleID_SearchAds'])){
				$clientIds .= '<clientIds>'.$child_val['googleID_SearchAds'].'</clientIds>';	
			}
		}
		$param = "<ns1:getBulkApprovalStatus xmlns:ns1=\"$namespace\">".$clientIds."</ns1:getBulkApprovalStatus>";

		// invoke web service
		$response = $client->call('getBulkApprovalStatus', $param, $namespace);
		
		//$this->showRequestResponse($client);
		$response = $response['return'];
		
		foreach($response as $key=>$val){
			$publishers['approvalStatus'][$val['clientId']] = $val['approvalStatus']['value'];
		}
		//echo "<pre>";print_r($publishers);echo "</pre>";
		return $publishers;
	}

	function get_bulk_association_status_deprecated($publishers){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$this->config->item('developer_client_id', 'adsense')."</client_id>";
		$header = $email . $password . $client_id;
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		$client->setHeaders($header);
		// setting the parameter
		$clientIds = '';
		foreach($publishers as $child_key=>$child_val){
			if(!empty($child_val['googleID_ContentAds'])){
				$clientIds .= '<clientIds>'.$child_val['googleID_ContentAds'].'</clientIds>';
			}
			elseif(!empty($child_val['googleID_SearchAds'])){
				$clientIds .= '<clientIds>'.$child_val['googleID_SearchAds'].'</clientIds>';	
			}
		}
		$param = "<ns1:getBulkAssociationStatus xmlns:ns1=\"$namespace\">".$clientIds."</ns1:getBulkAssociationStatus>";

		// invoke web service
		$response = $client->call('getBulkAssociationStatus', $param, $namespace);
		//$this->showRequestResponse($client);
		$response = $response['return'];
		
		foreach($response as $key=>$val){
			$publishers['associationStatus'][$val['clientId']] = $val['associationStatus']['value'];
		}
		
		return $publishers;
	}

	function get_bulk_association_status($publishers){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAccountDataForExistingPublisher';
			    //$publisher_account_id = 'ca-pub-3473562081766876';//lilindead
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    $result = $example->render($publishers);
				$this->adsensehostauth_admin->refreshToken();
				$associationStatus = array();
				foreach($result as $key=>$val){
					$associationStatus[$val['id']] = $val['status'];	
				}
				
				//echo "<pre>";print_r($associationStatus);echo "</pre>";exit;
				return $associationStatus;
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function create_content_ads($accountID){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$info = $this->publisher->get_publisher_by_account_id($accountID);
			//echo "<pre>";print_r($info);echo "</pre>";exit;
			$publisher_info = $info[0];
			$ori_publisher_info = $publisher_info;
			
			$result = array_diff($publisher_info,$ori_publisher_info);
			if(!empty($result)){// get update info, and update the database
				$this->publisher->insert_info($publisher_info);
			}
			if(empty($publisher_info['synServiceTypes'])){
				$publisher_info['synServiceTypes'] = $this->get_all_ad_clients_for_publisher($accountID);
			}
			//echo "<pre>";print_r($publisher_info);echo "</pre>";
			//$publisher_info['channelName'] = $this->get_afc_channels($accountID);
			//$publisher_info['hostChannelName'] = $this->get_adgeek_host_channels();
			//echo "<pre>";print_r($publisher_info);echo "</pre>";
			$this->load->view('backyard/create_content_ads', $publisher_info);	
		}
	}
	
	function create_search_ads($googleID){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$info = $this->publisher->get_publisher_by_afs_id($googleID);
			$publisher_info = $info[0];
			$ori_publisher_info = $publisher_info;
			
			if(empty($publisher_info['entityType'])){
				$publisher_info['entityType'] = $this->get_publisher_entityType_by_afs_id($googleID);
			}
			
			if(empty($publisher_info['websiteUrl'])){
				$publisher_info['websiteUrl'] = $this->get_publisher_websiteUrl_by_google_id($googleID);
			}
			
			if(empty($publisher_info['websiteLocale'])){
				$publisher_info['websiteLocale'] = $this->get_publisher_websiteLocale_by_google_id($googleID);
			}
			
			if(empty($publisher_info['usersPreferredLocale'])){
				$publisher_info['usersPreferredLocale'] = $this->get_publisher_usersPreferredLocale_by_google_id($googleID);
			}
			
			
			if(empty($publisher_info['synServiceTypes'])){
				$publisher_info['synServiceTypes'] = $this->get_publisher_synServiceTypes_by_google_id($googleID);
			}
			
			$result = array_diff($publisher_info,$ori_publisher_info);
			if(!empty($result)){// get update info, and update the database
				$this->publisher->insert_info($publisher_info);
			}
			
			
			$publisher_info['channelName'] = $this->get_afs_channels($googleID);
			$publisher_info['hostChannelName'] = $this->get_adgeek_host_channels();
			$this->load->view('backyard/create_search_ads', $publisher_info);	
		}
	}
	
	function show_content_ads($accountID){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$afc = array();
			$afc['accountID'] = $accountID;
			$afc['table_header'] = $this->config->item('show_header_afc', 'publisher');
			//echo "<pre>";print_r($afc);echo "</pre>";
			$afc['hostCustomChannels'] = $this->get_adgeek_host_channels();

			$afc['adunits'] = $this->get_all_ad_units_for_publisher($accountID);
			//echo "<pre>";print_r($afc);echo "</pre>";exit;
			//$afc['afc_info'] = $this->publisher->get_afc_overview($googleID);
			$this->load->view('backyard/show_content_ads', $afc);	
		}	
	}
	
	function show_content_ads_deprecated($googleID){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$afc = array();
			$afc['table_header'] = $this->config->item('show_header_afc', 'publisher');
			$afc['afc_info'] = $this->publisher->get_afc_overview($googleID);
			$this->load->view('backyard/show_content_ads', $afc);	
		}	
	}
	
	function show_search_ads($googleID){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$afc = array();
			$afc['table_header'] = $this->config->item('show_header_afs', 'publisher');
			$afc['afs_info'] = $this->publisher->get_afs_overview($googleID);
			$this->load->view('backyard/show_search_ads', $afc);	
		}	
	}
	
	function get_afc_code(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post(NULL, TRUE);
			$code = $this->publisher->get_afc_code($data);
			$show['snippet'] = urldecode($code[0]['code']);
			$this->load->view('backyard/code', $show);	
		}
	}
	
	function get_afs_code(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post(NULL, TRUE);
			$code = $this->publisher->get_afs_code($data);
			$show['snippet'] = urldecode($code[0]['code']);
			$this->load->view('backyard/code', $show);	
		}
	}
	
	function create_afc_channel_form(){
		$data = $this->input->post(NULL, TRUE);
		echo $this->load->view('backyard/create_afc_channel_form', $data,true);
	}
	
	function create_afs_channel_form(){
		$data = $this->input->post(NULL, TRUE);
		echo $this->load->view('backyard/create_afs_channel_form', $data,true);
	}
	
	function create_host_channel_form(){
		echo $this->load->view('backyard/create_host_channel_form', '',true);
	}
	
	function create_afc_channel(){
		$data = $this->input->post();
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$data['googleID']."</client_id>";
		$header = $email . $password . $client_id;
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>ContentAds</value></synServiceType></ns1:getSyndicationService>";

		// invoke web service
		$response = $client->call('getSyndicationService', $param, $namespace);
		$response = $response['return'];
		$synServiceId = $response['id'];
		
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/ChannelService?wsdl';
		$client = new soapclientnusoap($wsdl,true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		
		$param = '<ChannelService_Data>';
		$param .= '<name>'.$data['name'].'</name>';
		$param .= '<status><value>Active</value></status>';
		$param .= '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		$param .= '</ChannelService_Data>';
		$param = "<ns1:createChannel xmlns:ns1=\"$namespace\">".$param."</ns1:createChannel>";
		/*
		echo $data['name']."<br>";
		echo mb_detect_encoding($data['name']);exit;
		*/
		// invoke web service
		$response = $client->call('createChannel', $param, $namespace);
		$json = array();
		$allNewChannels = '';
		if(!empty($client->detail)){
			$json['status'] = 'false';
			$json['msg'] = 'ERROR CODE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']."<br><br>";
			$json['msg'] .= 'ERROR MESSAGE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['message']."<br><br>";
			$json['msg'] .= 'DETAIL：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['triggerDetails']."<br>";
			
		}
		elseif(isset($response['return']['name'])){
			$channel_arr = $this->get_afc_channels($data['googleID']);
			
			foreach($channel_arr as $key=>$val){
				$allNewChannels.='<option value="'.$key.'">'.$val.'</option>';	
			}	
			$json['status'] = 'true';
			$json['msg'] = '新增成功';
			$json['allNewChannels'] = $allNewChannels;
		}
		
		echo json_encode($json);
		//echo "<pre>";print_r($response['return']);echo "</pre>";exit;
	} 
	
	function create_afs_channel(){
		$data = $this->input->post();
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$data['googleID']."</client_id>";
		$header = $email . $password . $client_id;
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>SearchAds</value></synServiceType></ns1:getSyndicationService>";

		// invoke web service
		$response = $client->call('getSyndicationService', $param, $namespace);
		$response = $response['return'];
		$synServiceId = $response['id'];
		
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/ChannelService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = '<ChannelService_Data>';
		$param .= '<name>'.$data['name'].'</name>';
		$param .= '<status><value>Active</value></status>';
		$param .= '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		$param .= '</ChannelService_Data>';
		$param = "<ns1:createChannel xmlns:ns1=\"$namespace\">".$param."</ns1:createChannel>";
		
		// invoke web service
		$response = $client->call('createChannel', $param, $namespace);
		$json = array();
		$allNewChannels = '';
		if(!empty($client->detail)){
			$json['status'] = 'false';
			$json['msg'] = 'ERROR CODE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']."<br><br>";
			$json['msg'] .= 'ERROR MESSAGE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['message']."<br><br>";
			$json['msg'] .= 'DETAIL：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['triggerDetails']."<br>";
			
		}
		elseif(isset($response['return']['name'])){
			$channel_arr = $this->get_afs_channels($data['googleID']);
			
			foreach($channel_arr as $key=>$val){
				$allNewChannels.='<option value="'.$key.'">'.$val.'</option>';	
			}	
			$json['status'] = 'true';
			$json['msg'] = '新增成功';
			$json['allNewChannels'] = $allNewChannels;
		}
		
		echo json_encode($json);
		//echo "<pre>";print_r($response['return']);echo "</pre>";exit;
	}
	
	function create_host_channel(){
		$data = $this->input->post();
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$this->config->item('developer_client_id', 'adsense')."</client_id>";
		$header = $email . $password . $client_id;
		
		$synServiceId = $this->config->item('developer_client_host_id', 'adsense');
		//echo 'synid:'.$synServiceId;exit;
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/ChannelService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = '<ChannelService_Data>';
		$param .= '<name>'.$data['name'].'</name>';
		$param .= '<status><value>Active</value></status>';
		$param .= '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		$param .= '</ChannelService_Data>';
		$param = "<ns1:createChannel xmlns:ns1=\"$namespace\">".$param."</ns1:createChannel>";
		
		// invoke web service
		$response = $client->call('createChannel', $param, $namespace);
		//$this->showRequestResponse($client);exit;
		$json = array();
		$allNewChannels = '';
		if(!empty($client->detail)){
			$json['status'] = 'false';
			$json['msg'] = 'ERROR CODE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']."<br><br>";
			$json['msg'] .= 'ERROR MESSAGE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['message']."<br><br>";
			$json['msg'] .= 'DETAIL：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['triggerDetails']."<br>";
			
		}
		elseif(isset($response['return']['name'])){
			if(!$this->publisher->insert_new_host_channel($response['return'])){
				$json['status'] = 'false';
				$json['msg'] = '新增失敗';	
			}
			else{
				$channel_arr = $this->get_adgeek_host_channels();
				
				foreach($channel_arr as $key=>$val){
					$allNewChannels.='<option value="'.$key.'">'.$val.'</option>';	
				}	
				$json['status'] = 'true';
				$json['msg'] = '新增成功';
				$json['allNewHostChannels'] = $allNewChannels;	
			}
		}
		
		echo json_encode($json);
	}
	
	function get_afc_channels_deprecated($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>ContentAds</value></synServiceType></ns1:getSyndicationService>";
		
		// invoke web service
		
		$response = $client->call('getSyndicationService', $param, $namespace);
		// get back the response
		$response = $response['return'];
		$synServiceId = $response['id'];
		
		// setup client soap for another webservice
		$wsdl = $server . '/api/adsense/v3/AdSenseForContentService?wsdl';
		$client = new soapclientnusoap($wsdl,true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting up parameter
		$param = '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		
		$param = "<ns1:getChannels xmlns:ns1=\"$namespace\">" . $param . "</ns1:getChannels>";
		
		// invoke the web service
		$response = $client->call('getChannels', $param, $namespace);
		$channelsName = array(''=>'-');
		if(isset($response['return']['name'])){
			$channelsName[$response['return']['name']] = $response['return']['name'];
		}
		else{
			foreach($response['return'] as $key=>$val){
				$channelsName[$val['name']] = $val['name'];
			}	
		}
		
		return $channelsName; 
	}
	
	function get_afs_channels($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>SearchAds</value></synServiceType></ns1:getSyndicationService>";
		
		// invoke web service
		
		$response = $client->call('getSyndicationService', $param, $namespace);
		// get back the response
		$response = $response['return'];
		$synServiceId = $response['id'];
		
		// setup client soap for another webservice
		$wsdl = $server . '/api/adsense/v3/AdSenseForSearchService?wsdl';
		$client = new soapclientnusoap($wsdl,true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting up parameter
		$param = '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		
		$param = "<ns1:getChannels xmlns:ns1=\"$namespace\">" . $param . "</ns1:getChannels>";
		
		// invoke the web service
		$response = $client->call('getChannels', $param, $namespace);
		$channelsName = array(''=>'-');
		if(isset($response['return']['name'])){
			$channelsName[$response['return']['name']] = $response['return']['name'];
		}
		else{
			foreach($response['return'] as $key=>$val){
				$channelsName[$val['name']] = $val['name'];
			}	
		}
		
		return $channelsName; 
	}
	
	function get_adgeek_host_channels_deprecated(){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$this->config->item('developer_client_id', 'adsense')."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		
		$synServiceId = $this->config->item('developer_client_host_id', 'adsense');
		
		// setup client soap for another webservice
		$wsdl = $server . '/api/adsense/v3/AdSenseForContentService?wsdl';
		$client = new soapclientnusoap($wsdl,true);
		$client->soap_defencoding = 'UTF-8';
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting up parameter
		$param = '<synServiceId>'.$synServiceId.'</synServiceId>';
		$param .= '<type><value>Custom</value></type>';
		$param .= '<synServiceType><value>ContentAds</value></synServiceType>';
		
		$param = "<ns1:getChannels xmlns:ns1=\"$namespace\">" . $param . "</ns1:getChannels>";
		
		// invoke the web service
		$response = $client->call('getChannels', $param, $namespace);
		//$this->showRequestResponse($client);exit;
		$channelsName = array(''=>'-');
		if(isset($response['return']['name'])){
			if($response['return']['status']['value']=='Active'){
				$channelsName[$response['return']['name']] = $response['return']['name'];
			}
		}
		else{
			foreach($response['return'] as $key=>$val){
				if($val['status']['value']=='Active'){
					$channelsName[$val['name']] = $val['name'];
				}
			}	
		}
		
		return $channelsName; 
	}

	function get_adgeek_host_channels(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
				$data = array();
			  $data['ad_host_client_id'] = $this->config->item('developer_client_host_id', 'adsense');
			  $data['max_page_size'] = 1000;
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAllCustomChannelsForHost';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($data);
				$this->adsensehostauth_admin->refreshToken();
				return $result;
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function add_custom_channel_to_host(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
				$data = $this->input->post(NULL, TRUE);
			  $data['ad_host_client_id'] = $this->config->item('developer_client_host_id', 'adsense');;
			  $data['channel_name'] = $data['newCustomChannel'];
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'AddCustomChannelToHost';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($data);
				$this->adsensehostauth_admin->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function delete_custom_channel_on_host(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
				$data = array();
				$data['host_ad_client_id'] = $this->config->item('developer_client_host_id', 'adsense');
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'DeleteCustomChannelOnHost';
				
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($data);
				$this->adsensehostauth_admin->refreshToken();
				return $result;
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function get_publisher_entityType_by_afc_id($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getEntityType xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getEntityType>";
		
		// invoke web service
		
		$response = $client->call('getEntityType', $param, $namespace);
		//$this->showRequestResponse($client);
		// get back the response
		//echo "<pre>";print_r($response);echo "</pre>";
		return $response['return']['value'];
	}

	function get_publisher_entityType_by_afs_id($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getEntityType xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getEntityType>";
		
		// invoke web service
		
		$response = $client->call('getEntityType', $param, $namespace);
		//$this->showRequestResponse($client);
		// get back the response
		//echo "<pre>";print_r($response);echo "</pre>";
		return $response['return']['value'];
	}

	function get_publisher_websiteUrl_by_google_id($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getWebsiteUrl xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getWebsiteUrl>";
		
		// invoke web service
		
		$response = $client->call('getWebsiteUrl', $param, $namespace);
		
		// get back the response
		return $response['return'];
	}

	function get_publisher_websiteLocale_by_google_id($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getWebsiteLocale xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getWebsiteLocale>";
		
		// invoke web service
		
		$response = $client->call('getWebsiteLocale', $param, $namespace);
		
		// get back the response
		
		return $response['return'];
	}

	function get_publisher_usersPreferredLocale_by_google_id($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getUsersPreferredLocale xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getUsersPreferredLocale>";
		
		// invoke web service
		
		$response = $client->call('getUsersPreferredLocale', $param, $namespace);
		
		// get back the response
		
		return $response['return'];
	}

	function get_publisher_synServiceTypes_by_google_id_deprecated($googleID){
		$server = $this->config->item('API_server', 'adsense');
		$namespace = 'http://www.google.com/api/adsense/v3';
		
		// Set up the authentication headers
		$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
		$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
		$client_id = "<client_id>".$googleID."</client_id>";
			
		
		$header = $email . $password . $client_id;	
		// creating soap client
		$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
		$client = new soapclientnusoap($wsdl, true);
		$client->soap_defencoding = 'UTF-8';
		
		// Set the headers; they are needed for authentication
		$client->setHeaders($header);
		// setting the parameter
		$param = "<ns1:getAllSyndicationServices xmlns:ns1=\"$namespace\"><dummy>1</dummy></ns1:getAllSyndicationServices>";
		
		// invoke web service
		
		$response = $client->call('getAllSyndicationServices', $param, $namespace);
		
		// get back the response
		$synServices = '';
		
		if(isset($response['return'][0])){ // multi syndication services
			foreach($response['return'] as $key=>$val){
				$synServices .= $val['type']['value'].'/';
			}
			$synServices = substr($synServices, 0, -1);
		}
		else{
			$synServices = $response['return']['type']['value'];
		}
		
		return $synServices;
	}

	function get_all_ad_clients_for_publisher($publisher_account_id){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAllAdClientsForPublisher';
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($publisher_account_id);
				$adClients = $result['items'];
				$content ='';
		       if (isset($adClients)) {
		         foreach ($adClients as $adClient) {
				   $content .= $adClient['productCode'].'/';
		        }
			   }
				$content = substr($content, 0, -1);
				$this->adsensehostauth_admin->refreshToken();
				return $content;
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function get_all_ad_clients_for_host(){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAllAdClientsForHost';
			    
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
				
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $result = $example->render();
				
			    printHtmlFooter();
				$this->adsensehostauth_admin->refreshToken();
				
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function save_search_box_style(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post();
			if(empty($data['AFSName'])){
				echo '請確實填寫：名稱（管理用）';
				exit;
			}
			//echo "<pre>";print_r($data);echo "</pre>";
			
			$getCode = $data['getCode'];
			unset($data['getCode']);
			//first: test the AFSName&googleID made the primary
			
			if(!$this->publisher->test_afs_info($data)){
				echo '名稱（管理用）重覆，請重新命名';
				exit;
			}
			$server = $this->config->item('API_server', 'adsense');
			$namespace = 'http://www.google.com/api/adsense/v3';
			
			// Set up the authentication headers
			
			$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
			$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
			$client_id = "<client_id>".$data['googleID']."</client_id>";
			$display_locale = "<display_locale>en_US</display_locale>";
			
			$header = $email . $password . $client_id . $display_locale;
			
			
			// creating soap client
			$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
			$client = new soapclientnusoap($wsdl,TRUE);
			$client->soap_defencoding = 'UTF-8';
			
			// Set the headers; they are needed for authentication
			$client->setHeaders($header);
			$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>SearchAds</value></synServiceType></ns1:getSyndicationService>";
			$response = $client->call('getSyndicationService', $param, $namespace);
			$response = $response['return'];
			$synServiceId = $response['id'];
			
			// creating soap client
			$wsdl = $server . '/api/adsense/v3/AdSenseForSearchService?wsdl';
			$client = new soapclientnusoap($wsdl,TRUE);
			$client->soap_defencoding = 'UTF-8';
			$client->setHeaders($header);
			
			$param = '<synServiceId>'.$synServiceId.'</synServiceId>
			<country>'.$data['country'].'</country>
			<searchType><value>'.$data['searchType'].'</value></searchType>
			<siteProperties>
			<encoding>'.$data['encoding'].'</encoding>
			<locale>'.$data['locale'].'</locale>
			</siteProperties>
			<searchOptions>
			<isSafeSearch>false</isSafeSearch>
			<showResultsInNewWindow>'.$data['showResultsInNewWindow'].'</showResultsInNewWindow>
			</searchOptions>';
			
			if($data['searchType'] == 'GoogleSiteSearch'){
				$domain_array = explode("\n", $data['domains']);
				foreach($domain_array as $key=>$val){
					$param .='<domains>'.$val.'</domains>';	
				}
				$param .= '<selectedDomain>'.$domain_array[0].'</selectedDomain>';	
				$data['selectedDomain'] = $domain_array[0];
			}
			else{
				$param .= '<domains></domains>';
				$param .= '<selectedDomain></selectedDomain>';
			}
			
			$param .= '<searchBoxStyle>
			<backgroundColor>'.$data['backgroundColor'].'</backgroundColor>
			<isButtonBelow>'.$data['isButtonBelow'].'</isButtonBelow>
			<isCustomStyle>'.$data['isCustomStyle'].'</isCustomStyle>
			<isLogoAbove>'.$data['isLogoAbove'].'</isLogoAbove>
			<logoType><value>'.$data['logoType'].'</value></logoType>
			<searchStyleName>'.$data['searchStyleName'].'</searchStyleName>
			<textBoxLength>'.$data['textBoxLength'].'</textBoxLength>
			<textColor>'.$data['textColor'].'</textColor>
			</searchBoxStyle>
			';
			if(empty($data['channelName'])){
				$param .= '<channelName xsi:nil="true"/>';	
			}
			else $param .= '<channelName>'.$data['channelName'].'</channelName>';
			
			$param = "<ns1:generateSearchBoxCode xmlns:ns1=\"$namespace\">" . $param . "</ns1:generateSearchBoxCode>";
			
			// invoke web service
			
			$response = $client->call('generateSearchBoxCode', $param, $namespace);
			//$this->showRequestResponse($client);exit;
			
			if(!empty($client->detail)){
				echo 'ERROR CODE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']."<br><br>";
				echo 'ERROR MESSAGE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['message']."<br><br>";
				echo 'DETAIL：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['triggerDetails']."<br>";
			}
			else{
				$show['snippet'] = $response['return'];
				$my_snippet = htmlspecialchars($show['snippet'], ENT_QUOTES);
		  		
				$data['code'] = urlencode($my_snippet); 
				$this->publisher->insert_afs_info($data);
				if($getCode == 'true'){
					$this->load->view('backyard/code', $show);	
				}
				else echo '儲存完成！';
			}	
		}
	}
	
	function new_custom_channel_form(){
		$this->adsensehostauth_admin->authenticate('adgeek_backyard');
		
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			sleep(1);
			$this->load->view('backyard/new_custom_channel_form', '');
		}
	}
	
	function get_ad_code_form(){
		$this->adsensehostauth_admin->authenticate('adgeek_backyard');
		
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post();
			
			$adunits = $this->get_all_ad_units_for_publisher($data['accountID']);
			// echo "<pre>";print_r($adunits);echo "</pre>";exit;
			if(isset($adunits['items'])){
				$result['adUnits'] = $adunits['items'];
				$result['hostCustomChannels'] = $this->get_adgeek_host_channels();
				$result['accountID'] = $data['accountID'];
				$this->load->view('backyard/get_ad_code_form', $result);
			}
			else{
				echo 'No Result Was Found !';
			}
		}
	}
	
	function get_ad_code(){
		$this->adsensehostauth_admin->authenticate('adgeek_backyard');
		
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post();
			try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAdCode';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($data);
				$this->adsensehostauth_admin->refreshToken();
				//echo "<pre>";print_r($result);echo "</pre>";
				$this->load->view('backyard/code', $result);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
		}
	}
	
	function get_all_ad_units_for_publisher($account_id){
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  $publisher_id = array(
			  'publisher_account_id' => $account_id,
			  'publisher_ad_account_id' => 'ca-'.$account_id,
			  'max_page_size'			=> 1000
			  );
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'GetAllAdUnitsForPublisher';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $result = $example->render($publisher_id);
				$this->adsensehostauth_admin->refreshToken();
				return $result;
				//header('Location: '.$result['redirectUrl']);
				
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}
	
	function save_ad_style(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post();
			
			if(empty($data['name'])){
				echo '請確實填寫：廣告樣式名稱';
				exit;
			}
			//first: test the AFC name & accountID made the primary
			if(!$this->publisher->test_afc_info($data)){
				echo '廣告樣式名稱重覆，請重新命名';
				exit;
			}
		}
		
		try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
			
			try {
			  
			  $this->adsensehostauth_admin->authenticate('adgeek_backyard');
			  
			  	$action = 'AddAdUnitToPublisher';
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth_admin->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    $result = $example->render($data);
				
				$this->adsensehostauth_admin->refreshToken();
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
		
	}
	
	function save_ad_style_deprecated(){
		if (!$this->tank_auth->is_logged_in()) {// not logged in
			redirect('/auth/login');
		}
		else{
			$data = $this->input->post();
			if(empty($data['AFCName'])){
				echo '請確實填寫：名稱（管理用）';
				exit;
			}
			
			$getCode = $data['getCode'];
			unset($data['getCode']);
			//first: test the AFCName&googleID made the primary
			if(!$this->publisher->test_afc_info($data)){
				echo '名稱（管理用）重覆，請重新命名';
				exit;
			}
			$server = $this->config->item('API_server', 'adsense');
			$namespace = 'http://www.google.com/api/adsense/v3';
			
			// Set up the authentication headers
			
			$email = "<developer_email>".$this->config->item('developer_email', 'adsense')."</developer_email>";
			$password = "<developer_password>".$this->config->item('developer_password', 'adsense')."</developer_password>";
			$client_id = "<client_id>".$data['googleID']."</client_id>";
			
			$header = $email . $password . $client_id;
			
			
			// creating soap client
			$wsdl = $server . '/api/adsense/v3/AccountService?wsdl';
			$client = new soapclientnusoap($wsdl,TRUE);
			$client->soap_defencoding = 'UTF-8';
			
			// Set the headers; they are needed for authentication
			$client->setHeaders($header);
			$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>ContentAds</value></synServiceType></ns1:getSyndicationService>";
			$response = $client->call('getSyndicationService', $param, $namespace);
			$response = $response['return'];
			$synServiceId = $response['id'];
			
			// creating soap client
			$wsdl = $server . '/api/adsense/v3/AdSenseForContentService?wsdl';
			$client = new soapclientnusoap($wsdl,TRUE);
			$client->soap_defencoding = 'UTF-8';
			$client->setHeaders($header);
			
			// setting up adstyle parameter
			$ads_param = '<adStyle>';
			$ads_param .= "<name>".$data['name']."</name>";
			$ads_param .= '<borderColor>'.$data['borderColor'].'</borderColor>';
			$ads_param .= '<backgroundColor>'.$data['backgroundColor'].'</backgroundColor>';
			$ads_param .= '<titleColor>'.$data['titleColor'].'</titleColor>';
			$ads_param .= '<textColor>'.$data['textColor'].'</textColor>';
			$ads_param .= '<urlColor>'.$data['urlColor'].'</urlColor>';
			$ads_param .= '</adStyle>';
			
			// setting up parameter
			$param = '<synServiceId>'.$synServiceId.'</synServiceId>';
			$param .= $ads_param;
			$param .= '<adUnitType><value>'.$data['adUnitType'].'</value></adUnitType>';
			$param .= '<layout><value>'.$data['layout'].'</value></layout>';
			
			if($data['alternate'] == 'nil'){
				$param .= '<alternate xsi:nil="true"/>';	
			}
			else $param .= '<alternate>'.$data['alternate'].'</alternate>';
			
			$param .= '<isFramedPage type="xsd:boolean">'.$data['isFramedPage'].'</isFramedPage>';
			
			if($data['channelName'] == 'nil'){
				$param .= '<channelName xsi:nil="true"/>';	
			}
			else $param .= '<channelName>'.$data['channelName'].'</channelName>';
			
			$param .= '<cornerStyles><value>'.$data['cornerStyles'].'</value></cornerStyles>';
			
			if($data['hostChannelNames'] == 'nil'){
				$param .= '<hostChannelNames xsi:nil="true"/>';	
			}
			else $param .= '<hostChannelNames>'.$data['hostChannelNames'].'</hostChannelNames>';
			
			$param = "<ns1:generateAdCode xmlns:ns1=\"$namespace\">" . $param . "</ns1:generateAdCode>";
			// invoke web service
			$response = $client->call('generateAdCode', $param, $namespace);
			
			if(!empty($client->detail)){
				echo 'ERROR CODE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['code']."<br><br>";
				echo 'ERROR MESSAGE：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['message']."<br><br>";
				echo 'DETAIL：'.$client->detail['AdSenseApiExceptionFault']['AdSenseApiException']['triggerDetails']."<br>";
			}
			else{
				$show['snippet'] = $response['return'];
				$my_snippet = htmlspecialchars($show['snippet'], ENT_QUOTES);
		  		
				$data['code'] = urlencode($my_snippet); 
				$this->publisher->insert_afc_info($data);
				if($getCode == 'true'){
					$this->load->view('backyard/code', $show);	
				}
				else echo '儲存完成！';
			}	
		}
	}

	function showSnippet($snippet) {
	  $text = $this->toHtml($snippet, ENT_QUOTES);
	  return $text;
	}
	function showSoapClientError($err) {
	  echo '<h2>Soap Client Error</h2>' . "\n";
	  echo '<pre>' . $err . '</pre>';
	  echo "\n";
	}
	function showMyErrors($client) {
	  // print the soap
	  $this->showRequestResponse($client);
	
	  // print the error information
	  echo '<h2>Fault Code</h2>' . "\n";
	  echo "<b>Fault:</b>  {$client->fault}<br>\n";
	  echo "<b>Code:</b> {$client->faultcode}<br>\n";
	  echo "<b>String:</b> {$client->faultstring}<br>\n";
	  echo "<b>Detail:</b> {$client->faultdetail}<br>\n";
	}
	

	function toHtml($text)
	{
	  $my_text = htmlspecialchars($text, ENT_QUOTES);
	  $remove = array ("&lt;", " xmlns");
	  $insert = array ("<br>&lt;", "<br>    xmlns");
	  $my_text = str_replace($remove, $insert, $my_text);
	  return $my_text;
	}
	
	function showRequestResponse($client) {
	  // print request
	  echo '<h2>Request</h2>' . "\n";
	  echo '<pre>' . $this->toHtml($client->request) . '</pre>';
	  echo "\n";
	
	  // print response
	  echo '<h2>Response</h2>'. "\n";
	  echo '<pre>' . $this->toHtml($client->response) . '</pre>';
	  echo "\n";
	
	  // Uncomment the following lines to print debug statements
	  /*
	  echo '<h2>Debug</h2>' . "\n";
	  echo '<pre>' . toHtml($client->debug_str) . '</pre>';
	  echo "\n";
	  */
	}
}

/* End of file backyard.php */
/* Location: ./application/controllers/backyard.php */
